package fr.emn.fil.soc.gr3.controllers;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JOptionPane;

import org.apache.cxf.jaxrs.client.JAXRSClientFactory;

import fr.emn.fil.soc.gr3.Main;
import fr.emn.fil.soc.gr3.controllers.enums.EnumDialogConnexionController;
import fr.emn.fil.soc.gr3.entites.Compte;
import fr.emn.fil.soc.gr3.restws.ProtocoleCommunication;
import fr.emn.fil.soc.gr3.views.DialogConnexion;

public class DialogConnexionController implements ActionListener {

	DialogConnexion dialog;
	EnumDialogConnexionController type;

	public DialogConnexionController(DialogConnexion dialog,
			EnumDialogConnexionController type) {
		super();
		this.dialog = dialog;
		this.type = type;
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		switch (type) {
		case BTN_OK:
			String login = dialog.getTextField_login().getText();
			String password = String.valueOf(dialog.getTextField_password()
					.getPassword());

			ProtocoleCommunication com = JAXRSClientFactory.create(
					Main.BASE_SERVICE_URL, ProtocoleCommunication.class);
			Compte compte = com.authentifier(login, password);
			if (compte != null) {
				dialog.getParent().setCompteCourant(compte);
				JOptionPane.showMessageDialog(dialog, "Bienvenue "+compte.getLogin(), "Connexion OK", JOptionPane.INFORMATION_MESSAGE);
				dialog.dispose();
			} else {
				dialog.getParent().setCompteCourant(null);
				JOptionPane.showMessageDialog(dialog,
						"Utilisateur et/ou mot de passe incorrecte", "Erreur",
						JOptionPane.ERROR_MESSAGE);
			}

			dialog.getParent().setStateApplication();
			break;
		case BTN_ANNULER:
			dialog.dispose();
			break;

		default:
			break;
		}

	}

}
